package com.itheima.controller;

import com.itheima.entity.Result;
import com.itheima.entity.StatusCode;
import com.itheima.utils.CheckUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/createCode")
@CrossOrigin(allowCredentials="true", allowedHeaders="*", methods={RequestMethod.GET,RequestMethod.POST}, origins="*")
public class CreateCodeController {

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/validCode")
    public Result validCode(@RequestBody Map<String,String> map) {
        String  phone=map.get("info");
        System.out.println(phone);
        if (!CheckUtils.checkMobileNumber(phone)) {
            if (!CheckUtils.checkEmail(phone)) {
                return new Result("error", "输入的邮箱或手机号格式有误");
            }
        }
        //生成6位随机数
        final String code = (long) (Math.random() * 1000000) + "";
        System.out.println(code);

        //存入缓存
        redisTemplate.opsForValue().set("SMS:" + phone, code, 5, TimeUnit.MINUTES);

        return new Result("success", "生成验证码成功");
    }
}
